package com.lishem.carl._07tree;

import com.lishem.common.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * https://leetcode.cn/problems/minimum-depth-of-binary-tree/
 * <p>
 * 给定一个二叉树，找出其最小深度。
 * <p>
 * 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
 * <p>
 * 说明：叶子节点是指没有子节点的节点。
 */
public class _12LetCode104_二叉树的最大深度 {

    /**
     * 非递归
     */
    public int minDepth1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int count = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            count++;
            for (int i = 0; i < size; i++) {
                root = queue.poll();
                if (root.left == null && root.right == null) {
                    return count;
                }
                if (root.left != null) {
                    queue.add(root.left);
                }
                if (root.right != null) {
                    queue.add(root.right);
                }
            }
        }
        return -1;
    }

    /**
     * 递归
     */
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        int minDepth1 = minDepth(root.left);
        int minDepth2 = minDepth(root.right);
        if (root.left == null || root.right == null) {
            // 没子节点算出来是0 ，加上无伤大雅
            return minDepth1 + minDepth2 + 1;
        }
        // 左右子树都有的时候
        return Math.min(minDepth1, minDepth2) + 1;
    }

    public static void main(String[] args) {
        _12LetCode104_二叉树的最大深度 sol = new _12LetCode104_二叉树的最大深度();
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(sol.minDepth(root));
        System.out.println(sol.minDepth1(root));

        TreeNode root1 = new TreeNode(2);
        root1.right = new TreeNode(3);
        root1.right.right = new TreeNode(4);
        root1.right.right.right = new TreeNode(5);
        root1.right.right.right.right = new TreeNode(6);
        System.out.println(sol.minDepth(root1));
        System.out.println(sol.minDepth1(root1));

    }
}
